package com.service.impl;

import com.dao.BabyMessageDao;
import com.dao.BabyUserDao;
import com.entity.BabyMessageDO;
import com.entity.BabyUserDO;
import com.service.PushMessageService;
import com.util.Result;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.*;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Author：hanll
 * ClassName：PushMessageImpl
 * Date：2022/8/28 12:12
 * Version：1.0
 * Description：
 */
@Service
public class PushMessageImpl implements PushMessageService {

    public static Logger logger = LoggerFactory.getLogger(PushMessageImpl.class);

    @Resource
    private WxMpService wxMpService;

    @Resource
    private BabyUserDao babyUserDao;

    @Resource
    private BabyMessageDao babyMessageDao;

    private String tqUrl = "http://t.weather.itboy.net/api/weather/city/101220101";

    @Override
    public Result orderStatus() {
        try {
            List<BabyUserDO> list = babyUserDao.findAll();
            Optional<BabyMessageDO> optional = babyMessageDao.findById("1");
            BabyMessageDO babyMessageDO = optional.get();
            for (BabyUserDO babyUserDO : list) {
                URL url = new URL(tqUrl);
                InputStreamReader isReader =  new InputStreamReader(url.openStream(),"UTF-8");//“UTF- 8”万国码，可以显示中文，这是为了防止乱码
                BufferedReader br = new BufferedReader(isReader);//采用缓冲式读入
                String str;
                while((str = br.readLine()) != null){
                    String regex="\\p{Punct}+";
                    String digit[]=str.split(regex);
                    WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
                    templateMessage.setTemplateId(babyUserDO.getTemplateId());
                    templateMessage.setToUser(babyUserDO.getZdrmb());
                    List<WxMpTemplateData> data = Arrays.asList(
                            new WxMpTemplateData("xm", babyUserDO.getXm()),
                            new WxMpTemplateData("cs", digit[22]+digit[18]),
                            new WxMpTemplateData("sj", digit[49]+"年"+digit[50]+"月"+digit[51]+"日"+digit[53]),
                            new WxMpTemplateData("wd", digit[47]+"~"+digit[45]),
                            new WxMpTemplateData("wxts", digit[69]),
                            new WxMpTemplateData("sr", getBirthday(babyUserDO.getSr(), babyMessageDO.getSrxx())),
                            new WxMpTemplateData("baby", babyMessageDO.getXx()),
                            new WxMpTemplateData("lajnr", getImportantEvents("11-17", babyMessageDO.getJnrxx()))
                    );
                    templateMessage.setData(data);
                    try {
                        wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                        logger.error("【微信模版消息】发送失败, {}", e);
                        return Result.error("【微信模版消息】发送失败, {}");
                    }
                }
                br.close();//网上资源使用结束后，数据流及时关闭
                isReader.close();
            }
            return Result.success();
        } catch (Exception e) {
            logger.error("失败", e);
            return Result.error("消息发送失败");
        }
    }

    @Override
    public Result findMessage() {
        try {
            BabyMessageDO babyMessageDO = babyMessageDao.findById("1").get();
            return Result.success(babyMessageDO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询消息成功");
        }
    }

    @Override
    public Result updMessage(String xx, String srxx, String jnrxx) {
        try {
            BabyMessageDO babyMessageDO = new BabyMessageDO();
            babyMessageDO.setId("1");
            babyMessageDO.setXx(xx);
            babyMessageDO.setSrxx(srxx);
            babyMessageDO.setJnrxx(jnrxx);
            babyMessageDao.save(babyMessageDO);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改发送消息成功");
        }
    }

    public String getImportantEvents(String sr, String jnrxx) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("MM-dd");
        Date date = new Date();
        String thisTime = format.format(date);
        Date date1 = format.parse(thisTime);
        Date date2 = format.parse(sr);
        String jnrthday = "";
        Integer a = (int) ((date1.getTime() - date2.getTime()) / (1000*3600*24));
        if (a < 0) {
            jnrthday = Math.abs(a) + "天";
        } else if (a > 0){
            jnrthday = 365 - a + "天";
        } else if (a == 0) {
            jnrthday = jnrxx;
        }
        return jnrthday;
    }

    public String getBirthday(String sr, String srxx) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("MM-dd");
        Date date = new Date();
        String thisTime = format.format(date);
        Date date1 = format.parse(thisTime);
        Date date2 = format.parse(sr);
        String birthday = "";
        Integer a = (int) ((date1.getTime() - date2.getTime()) / (1000*3600*24));
        if (a < 0) {
            birthday = Math.abs(a) + "天";
        } else if (a > 0){
            birthday = 365 - a + "天";
        } else if (a == 0) {
            birthday = srxx;
        }
        return birthday;
    }
}
